package sma.sync.model;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

public abstract class Folder {

	/** Log4J */
	protected static final Logger sLog = Logger.getLogger(Folder.class);


	protected File baseFolder;

	Map<String, File> filesTofolders = new HashMap<String, File>();

	/** for debugging purpose */
	Set<String> ignoredExtensions = new HashSet<String>();

	public Folder(File pSource) {
		baseFolder = pSource;
	}

	public void analyse() {
		this.recurseInDir(baseFolder);
		sLog.debug("filesTofolders.size()=" + filesTofolders.size() + " for " + baseFolder);
		sLog.info("ignoredExtensions=" + ignoredExtensions);
	}

	protected void recurseInDir(File pFolder) {
		sLog.debug("recurseInDir " + pFolder);
		File[] subFiles = pFolder.listFiles();
		for (int i = 0; i < subFiles.length; i++) {
			File file = subFiles[i];
			if (file.isDirectory()) {
				this.recurseInDir(file);
			} else {
				if (this.isMusicFile(file)) {
					this.addFile(pFolder, file);
					// } else {
					// sLog.debug("Not a music file: " + file);
				}
			}
		}
	}

	protected abstract void addFile(File pFolder, File pFile);

	private boolean isMusicFile(File pFile) {
		String ext = this.getFileExtension(pFile);
		if (ext.equals("mp3") || ext.equals("wma")) {
			return true;
		} else {
			ignoredExtensions.add(ext);
			return false;
		}

	}

	/**
	 * returned lowercase extension
	 * 
	 * @param pFile
	 * @return
	 */
	private String getFileExtension(File pFile) {
		String s1 = pFile.getName();
		final int s1Dot = s1.lastIndexOf('.');
		return s1.substring(s1Dot + 1).toLowerCase();
	}

}
